package com.example.smartcity.ui.notifications.activity

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import com.example.smartcity.databinding.ActivityPersonLoginBinding
import com.example.smartcity.logic.Repository
import com.example.smartcity.logic.Repository.coroutine
import com.example.smartcity.logic.util.Util.show
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * 智慧城市-用户登录
 */
class PersonLoginActivity : AppCompatActivity() {

    lateinit var mBinding: ActivityPersonLoginBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityPersonLoginBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        // 显示回退按钮
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        // 点击登录
        mBinding.edPost.setOnClickListener {
            // 调用挂起函数
            coroutine {
                login()
            }
        }


    }


    /**
     * 登录
     */
    private suspend fun login() {
        // 判断是否为空
        if (
            mBinding.edName.text.toString().isNotEmpty() &&
            mBinding.edPasswd.text.toString().isNotEmpty()
        ) {
            Repository.api.getLogin(JSONObject().apply {
                this.put("username", mBinding.edName.text.toString())
                this.put("password", mBinding.edPasswd.text.toString())
            }.toString().toRequestBody("application/json".toMediaType())).apply {
                // 判断是否请求成功
                if (this.code == 200) {
                    // 成功就将token存储到本地
                    getSharedPreferences("token", Context.MODE_PRIVATE)
                        .edit()
                        .putBoolean("user", true) // 存储登录状态
                        .putString("token", this.token.toString())
                        .apply()
                    // 销毁该界面
                    finish()
                } else {
                    this.msg?.show()
                }
            }
        }else "账号或密码不能为空!".show()

    }


    // 点击销毁该页面
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}